using System;
using UnityEngine;
using UnityEngine.UI;

public class EE_Building_Controller : MonoBehaviour
{
    public EE_Data.BuildingID id = EE_Data.BuildingID.townhall;
    private static EE_Building_Controller instance = null; public static EE_Building_Controller Instance {get{return instance;} set {instance = value;} }

    [HideInInspector] public EE_Data.Building  data = new EE_Data.Building();
    [HideInInspector] public EE_UI_Button collectButton = null;
    [HideInInspector] public bool collecting = false;// 是否正在收集
    [HideInInspector] public EE_UI_Bar buildBar = null;
    // private EE_BuildGrid_Controller gridBuilder = null;

    [SerializeField] private int rows = 1;public int Rows {get{return rows;}set{rows = value;}}
    [SerializeField] private int cols = 1;public int Cols {get{return cols;}set{cols = value;}}
    
    [SerializeField] public MeshRenderer baseArea = null;
    
    [SerializeField] private Level[] levels = null;

    // 移动的位置(网格坐标)
    private int currentX = 0;public int CurrentX{get{return currentX;}set{currentX = value;}}
    private int currentY = 0;public int CurrentY{get{return currentY;}set{currentY = value;}}
    // 初始位置(网格坐标)
    private int X = 0;public int x{get{return X;}set{X = value;}}
    private int Y = 0;public int y{get{return Y;}set{Y = value;}}
    
    private bool isConfirmed = false;public bool IsConfirmed{get{return isConfirmed;}set{isConfirmed = value;}}
    private float genGoldTimer = 0;
    private float genGoldInterval = 1;
    
    [System.Serializable] public class Level
    {
        public int level = 1;
        public Sprite icon = null;
        public GameObject mesh = null;
    }

    public void Collect()
    {
        collectButton.gameObject.SetActive(false);
        collecting = true;
        // todo: 调用后端服务-资源收集
        bool isSuccess = true;
        if (isSuccess)
        {
            switch (id)
            {
                case EE_Data.BuildingID.townhall:
                    break;
                case EE_Data.BuildingID.goldmine:
                    EE_UI_Main.Instance.goldText.text = (int.Parse(EE_UI_Main.Instance.goldText.text) + data.storage).ToString();
                    break;
                case EE_Data.BuildingID.goldstorage:
                    break;
                case EE_Data.BuildingID.elixer:
                    break;
                case EE_Data.BuildingID.elixerstorage:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            collecting = false;
            data.storage = 0;
            AdjustUI();
        }
    }

    private void Update()
    {
        AdjustUI();
    }

    public void AdjustUI()
    {
        if (collectButton)// 只有带有资源收集按钮的建筑， 才需要添加按钮
        {
            switch (id)
            {
                case EE_Data.BuildingID.townhall:
                    break;
                case EE_Data.BuildingID.goldmine:
                    // 模拟金矿每秒生产 6个 金币
                    genGoldTimer += Time.deltaTime;
                    if (genGoldTimer > genGoldInterval)
                    {
                        genGoldTimer -= genGoldInterval;
                        data.storage += 6;
                    }
                    // 当产量大于可收集阈值 并且 不处于建造中 时，才显示收集按钮
                    if (data.storage > EE_Data.minGoldCollect && !data.constructing)
                    {
                        collectButton.gameObject.SetActive(!collecting);
                    }
                    else
                    {
                        collectButton.gameObject.SetActive(false);
                    }
                    break;
                case EE_Data.BuildingID.goldstorage:
                    break;
                case EE_Data.BuildingID.elixer:
                    break;
                case EE_Data.BuildingID.elixerstorage:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            // 利用 建筑(右上角)的网格坐标 获得 世界坐标
            Vector3 end = EE_UI_Main.Instance.grid.GetCenterPosition(this);
            // 屏幕左下角和屏幕右上角 在平面上的坐标
            Vector3 planeDownLeft = EE_MainCamera_Controller.Instance.CameraScreenPositionToPlanePosition(Vector2.zero);
            Vector3 planeTopRight = EE_MainCamera_Controller.Instance.CameraScreenPositionToPlanePosition(new Vector2(Screen.width, Screen.height));
            // 计算屏幕在世界坐标上的宽度和高度
            float w = planeTopRight.x - planeDownLeft.x;
            float h = planeTopRight.z - planeDownLeft.z;
            // 建筑(右上角)相对于屏幕(平面坐标)左下角 在3d空间中的偏移
            float endW = end.x - planeDownLeft.x;
            float endH = end.z - planeDownLeft.z;
            // 建筑(右上角)在屏幕上 的位置
            Vector2 screenPoint = new Vector2(endW/w * Screen.width, endH/h * Screen.height);
            // X和V按钮 在屏幕上的位置 (需要将X和V按钮的锚点位置设为左下角),todo：鼠标移动速度太快会让 按钮的跟随 跟不上
            collectButton.rect.anchoredPosition = screenPoint;
        }
        // 处理进度条
        if (buildBar)
        {
            if (data.constructing)// 正在建造中
            {
                buildBar.AdjustUI();
                buildBar.gameObject.SetActive(true);
                // 利用 建筑(右上角)的网格坐标 获得 世界坐标
                Vector3 end = EE_UI_Main.Instance.grid.GetCenterPosition(this);
                // 屏幕左下角和屏幕右上角 在平面上的坐标
                Vector3 planeDownLeft = EE_MainCamera_Controller.Instance.CameraScreenPositionToPlanePosition(Vector2.zero);
                Vector3 planeTopRight = EE_MainCamera_Controller.Instance.CameraScreenPositionToPlanePosition(new Vector2(Screen.width, Screen.height));
                // 计算屏幕在世界坐标上的宽度和高度
                float w = planeTopRight.x - planeDownLeft.x;
                float h = planeTopRight.z - planeDownLeft.z;
                // 建筑(右上角)相对于屏幕(平面坐标)左下角 在3d空间中的偏移
                float endW = end.x - planeDownLeft.x;
                float endH = end.z - planeDownLeft.z;
                // 建筑(右上角)在屏幕上 的位置
                Vector2 screenPoint = new Vector2(endW/w * Screen.width, endH/h * Screen.height);
                // X和V按钮 在屏幕上的位置 (需要将X和V按钮的锚点位置设为左下角),todo：鼠标移动速度太快会让 按钮的跟随 跟不上
                buildBar.rect.anchoredPosition = screenPoint;
            }
            else
            {
                buildBar.gameObject.SetActive(false);
            }
        }
    }

    public void PlaceOnGrid(int x, int y)
    {
        currentX = x;
        currentY = y;
        X = x;
        Y = y;
        Vector3 position = EE_UI_Main.Instance.grid.GetCenterPosition(x, y, rows, cols);
        transform.position = position;
    }
    
    public void StartMovingOnGrid()
    {
        X = currentX;
        Y = currentY;
    }

    public void RemoveFromGrid()
    {
        instance = null;
        EE_UI_Build.Instance.SetStatus(false);
        EE_MainCamera_Controller.Instance.isPlacingBuilding = false;
        Destroy(gameObject);
    }

    // basePosition 没有移动时的位置
    // currentPosition 移动到的位置
    public void UpdateGridPosition(Vector3 basePosition, Vector3 currentPosition)
    {
        Vector3 dir =
            EE_UI_Main.Instance.grid.transform.TransformPoint(currentPosition) -
            EE_UI_Main.Instance.grid.transform.TransformPoint(basePosition);
        int xDis = Mathf.RoundToInt(dir.z / EE_UI_Main.Instance.grid.CellSize);
        int yDis = Mathf.RoundToInt(-dir.x / EE_UI_Main.Instance.grid.CellSize);
        
        currentX = X + xDis;
        currentY = Y + yDis;
        
        Vector3 position = EE_UI_Main.Instance.grid.GetCenterPosition(currentX, currentY, rows, cols);
        transform.position = position;
        // 设置底座颜色
        SetBaseColor();
    }

    private void SetBaseColor()
    {
        if (EE_UI_Main.Instance.grid.CanPlaceBuilding(this, currentX, currentY))
        {
            EE_UI_Build.Instance.buttonConfirm.GetComponent<Button>().interactable = true;
            baseArea.material.color = Color.green;//.sharedMaterial.color = Color.green;
            if (isConfirmed)
            {
                // 已被建造的建筑移动 且移到了正确位置, 启用[确认和取消]按钮
                EE_UI_Build.Instance.SetStatus(true);
            }
        }
        else
        {
            EE_UI_Build.Instance.buttonConfirm.GetComponent<Button>().interactable = false;
            baseArea.material.color = Color.red;//.sharedMaterial.color = Color.red;
            if (isConfirmed)
            {
                // 已被建造的建筑移动 且移到了错误位置, 禁用[确认和取消]按钮
                EE_UI_Build.Instance.SetStatus(false);
            }
        }
    }
    
    public void Selected()
    {
        EE_UI_BuildingOptions.Instance.SetStatus(true);
    }

    public void Deselected()
    {
        EE_UI_BuildingOptions.Instance.SetStatus(false);
        // 如果建筑在非法位置, 则弹回原始位置
        if (!EE_UI_Main.Instance.grid.CanPlaceBuilding(this, currentX, currentY))
        {
            PlaceOnGrid(X, Y);
            SetBaseColor();
        }
    }
}